<?php
/**
 *
 * @author ling
 * @url http://bbs.we7.cc/
 */
defined('IN_IA') or exit('Access Denied');

class junsion_wxtoolsModuleProcessor extends WeModuleProcessor
{
    public function respond(){
        global $_W;

        if ($this->message['msgtype'] == 'text' || ($this->message['msgtype'] == 'event' && $this->message['event'] == 'CLICK')) {
        	$openid = $this->message['from'];
        	$kword = strtolower($this->message['content']);
        	$rid = $this->rule;
        	load()->model('mc');
        	
        	if ($this->inContext){//答题验证回复答案
        		$aid = $_SESSION['junsion_wxtools_act_aid'];
        		$act = pdo_fetch("select starttime,endtime,nostarttips,endtips,scoretips from ".tablename($this->modulename."_act")." where id='{$aid}'");
        		if (empty($act)){
        			$this->endContext();
        			return $this->respText('活动已结束');
        		}
        		if ($act['starttime'] > time()){
        			$this->endContext();
        			return $this->respText($act['nostarttips']?$act['nostarttips']:'活动未开始');
        		}elseif ($act['endtime'] < time()){
        			$this->endContext();
        			return $this->respText($act['endtips']?$act['endtips']:'活动已结束');
        		}
        		
        		$code = pdo_fetch("select * from ".tablename($this->modulename."_codes")." where aid='{$aid}' and code='{$kword}'");
        		if (empty($code)){
        			$this->endContext();
        			return $this->respText('无效的口令！');
        		}
        		if ($code['mid']){
        			$this->endContext();
        			return $this->respText('该口令已使用过了！');
        		}
        		$mem = pdo_fetch('select id from ' . tablename($this->modulename.'_mem') . " where openid = '{$openid}' and uniacid='{$_W['uniacid']}'");
        		pdo_update($this->modulename."_codes",array('mid'=>$mem['id'],'usetime'=>time()),array('id'=>$code['id']));
        		$uid = mc_openid2uid($openid);
        		mc_credit_update($uid,'credit1',$code['score'],array($uid,$act['title']));
        		$score = pdo_fetchcolumn("select credit1 from ".tablename('mc_members')." where uid='{$uid}'");
        		$this->endContext();
        		return $this->respText(str_replace('#积分#', $code['score'], str_replace('#总分#', $score, $act['scoretips'])));
        	}
        	
        	$ACCESS_TOKEN = $this->getAccessToken();
        	$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$ACCESS_TOKEN}&openid={$openid}&lang=zh_CN";
        	load()->func('communication');
        	$json = ihttp_get($url);
        	$userInfo = @json_decode($json['content'], true);
        	$mem = pdo_fetch('select id from ' . tablename($this->modulename.'_mem') . " where openid = '{$openid}' and uniacid='{$_W['uniacid']}'");
        	if (empty($mem)){
        		pdo_insert($this->modulename.'_mem',array('uniacid'=>$_W['uniacid'],'openid'=>$openid,'nickname'=>$userInfo['nickname'],'avatar'=>$userInfo['headimgurl'],'createtime'=>time()));
        		$mem['id'] = pdo_insertid();
        	}
        	
        	$rule = pdo_fetch("select name from ".tablename('rule')." where id='{$rid}'");
        	if ($rule['name'] == 'junsion_wxtools_act'){//活动
        		$act = pdo_fetch("select * from ".tablename($this->modulename."_act")." where kword='{$kword}' and uniacid='{$_W['uniacid']}'");
        		if (empty($act)) return $this->respText('活动已结束');
        		if ($act['starttime'] > time()){
        			return $this->respText($act['nostarttips']?$act['nostarttips']:'活动未开始');
        		}elseif ($act['endtime'] < time()){
        			return $this->respText($act['endtips']?$act['endtips']:'活动已结束');
        		}
        		$this->beginContext();
        		$_SESSION['junsion_wxtools_act_aid'] = $act['id'];
        		return $this->respText($act['kwtips']);
        	}elseif ($rule['name'] == 'junsion_wxtools_rank'){
        		$set = pdo_fetch("select * from ".tablename($this->modulename."_scorerank")." where uniacid='{$_W['uniacid']}'");
        		$set = unserialize($set['ranks']);
        		$rule = $set['news'];
        		return $this->respNews(array(array('title'=>$rule['title'],'description'=>$rule['desc'],'picurl'=>toimage($rule['thumb']),'url'=>$this->buildSiteUrl($this->createMobileUrl('scorerank')))));
        	}elseif ($rule['name'] == 'junsion_wxtools_kw'){//关键字分组
        		$set = pdo_fetch("select * from ".tablename($this->modulename."_kword")." where uniacid='{$_W['uniacid']}'");
        		$set = unserialize($set['kwords']);
        		
        		foreach ($set as $value) {
        			if ($kword == $value['kword']){
        				if (!empty($value['fgid'])){
        					$acc = WeAccount::create($_W['uniacid']);
        					$data = $acc->fansTagTagging($openid, array($value['fgid']));
        					if(!is_error($data)) {
        						$fans = pdo_fetch("select groupid,uid from ".tablename('mc_mapping_fans')." where openid='{$openid}' and uniacid='{$_W['uniacid']}'");
	        					$data = $acc->fansTagBatchTagging($openid,$value['fgid']);
								if(!is_error($data)) {
									if($fans['groupid']) $tagid = $fans['groupid'].",".$value['fgid'];
									else $tagid = $value['fgid'];
									pdo_update('mc_mapping_fans', array('groupid' =>$tagid), array('uniacid' => $_W['uniacid'],'openid' => $openid));
								}
        					}
        				}
        				return $this->respText($value['tips']);
        			}
        		}
        		
        	}
        	
        }
        
    }
    
    private function getAccessToken() {
    	global $_W;
    	load()->model('account');
    	$acid = $_W['acid'];
    	if (empty($acid)) {
    		$acid = $_W['uniacid'];
    	}
    	$account = WeAccount::create($acid);
    	$token = $account->fetch_available_token();
    	return $token;
    }
    
    private function uploadImage($img)
    {
    	load()->func('communication');
    	$access_token = $this->getAccessToken();
    	$url = 'http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $access_token . '&type=image';
    	$ch1 = curl_init();
    	$data = array('media' => '@' . $img);
    	if (version_compare(PHP_VERSION, '5.5.0', '>')) {
    		$data = array('media' => curl_file_create($img));
    	}
    	curl_setopt($ch1, CURLOPT_URL, $url);
    	curl_setopt($ch1, CURLOPT_POST, 1);
    	curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
    	curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
    	curl_setopt($ch1, CURLOPT_POSTFIELDS, $data);
    	$content = @json_decode(curl_exec($ch1), true);
    	if (!(is_array($content))) {
    		$content = array('media_id' => '');
    	}
    	curl_close($ch1);
    	return $content['media_id'];
    }
    
}
